Position Management

Get a List of All Open Positions

get_positions(self, account_id, **params)


In [1]:
from datetime import datetime, timedelta
import pandas as pd
import oandapy
import configparser

config = configparser.ConfigParser()
config.read('../config/config_v1.ini')
account_id = config['oanda']['account_id']
api_key = config['oanda']['api_key']

oanda = oandapy.API(environment="practice", 
                    access_token=api_key)

In [2]:
trade_expire = datetime.now() + timedelta(days=1)
trade_expire = trade_expire.isoformat("T") + "Z"
fx_list = ["AUD_USD", "NZD_USD", "USD_JPY"]
for oo in fx_list:
    response = oanda.create_order(account_id,
                                  instrument = oo,
                                  units=1000,
                                  side="buy",
                                  type="market",
                                  expiry=trade_expire)

In [3]:
response = oanda.get_positions(account_id)
print(response)


{'positions': [{'avgPrice': 0.75083, 'units': 8000, 'side': 'buy', 'instrument': 'AUD_USD'}, {'avgPrice': 1.06433, 'units': 7000, 'side': 'buy', 'instrument': 'EUR_USD'}, {'avgPrice': 1.20372, 'units': 1000, 'side': 'buy', 'instrument': 'GBP_USD'}, {'avgPrice': 0.71598, 'units': 6000, 'side': 'buy', 'instrument': 'NZD_USD'}, {'avgPrice': 1.00742, 'units': 7000, 'side': 'buy', 'instrument': 'USD_CHF'}, {'avgPrice': 115.204, 'units': 1000, 'side': 'buy', 'instrument': 'USD_JPY'}]}

In [4]:
pd.DataFrame(response['positions'])


Out[4]:
avgPrice instrument side units
0 0.75083 AUD_USD buy 8000
1 1.06433 EUR_USD buy 7000
2 1.20372 GBP_USD buy 1000
3 0.71598 NZD_USD buy 6000
4 1.00742 USD_CHF buy 7000
5 115.20400 USD_JPY buy 1000

Get the Position for An Instrument

get_position(self, account_id, instrument, **params)


In [5]:
response = oanda.get_position(account_id, 
                              instrument="USD_JPY")
print(response)


{'avgPrice': 115.204, 'units': 1000, 'side': 'buy', 'instrument': 'USD_JPY'}

Close an Existing Position

close_position(self, account_id, instrument, **params)


In [6]:
response = oanda.close_position(account_id, 
                                instrument="USD_JPY")
print(response)


{'totalUnits': 1000, 'ids': [10618882484, 10618882724], 'instrument': 'USD_JPY', 'price': 115.19}

In [7]:
response = oanda.get_positions(account_id)
pd.DataFrame(response['positions'])


Out[7]:
avgPrice instrument side units
0 0.75083 AUD_USD buy 8000
1 1.06433 EUR_USD buy 7000
2 1.20372 GBP_USD buy 1000
3 0.71598 NZD_USD buy 6000
4 1.00742 USD_CHF buy 7000